package ch.cern

class MapJSTagLib {
  static namespace = "gm"

  def map = { attrs, body ->
    def mapInstance = attrs.mapInstance
    def points = attrs.points
    if (mapInstance != null)
      points = mapInstance.points

    out << """<script type="text/javascript">
          var infobulle;
          var map;
          function initialize()
          {
            var myOptions = {mapTypeId: google.maps.MapTypeId.ROADMAP};
            map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
            var bounds = new google.maps.LatLngBounds(); //will help the map display all the points
            infobulle = new google.maps.InfoWindow();
            
            """
    points?.each { out << """createMarker(map, bounds, ${it.latitude}, ${it.longitude},
      '${it.title}', '${it.description}<br/>${it.createdOn.format("dd MMM yyyy")}<br/>${it.tags}');""" }

    out << """
            //in the end set the map to fit the bounds
            map.fitBounds(bounds);
          }
          
          function createMarker(map, bounds, lat, lng, titre, description)
          {
            var latlng = new google.maps.LatLng(lat, lng);
            var marker = new google.maps.Marker({
              position: latlng,
              map: map,
              title: titre
            });
            
            google.maps.event.addListener(marker, 'click', function() {
              infobulle.setContent(description);
              infobulle.open(map, marker);
            });
            bounds.extend(latlng); //add the point the bounds
          }
          </script>"""
  }
}
